#include <my_head.h>

// 获取源文件大小 并 创建目标文件
int get_srcfile_len_and_create_destfile(const char *src_file, const char *dest_file){
    int fd = 0;
    // 获取源文件大小
    if(-1 == (fd = open(src_file, O_RDONLY))){
        ERR_LOG("open error");
    }
    int length = lseek(fd, 0, SEEK_END);
    close(fd);
    // 创建 清空 目标文件
    if(-1 == (fd = open(dest_file, O_WRONLY|O_CREAT|O_TRUNC, 0666))){
        ERR_LOG("open error");
    }
    close(fd);
    return length;
}

// 拷贝文件
int copy_file(const char *src_file, const char *dest_file, int offset, int cp_len){
    // 打开源文件和目标文件
    int fd_src = open(src_file, O_RDONLY);
    if(-1 == fd_src)
        ERR_LOG("open error");
    int fd_dest = open(dest_file, O_WRONLY);
    if(-1 == fd_dest)
        ERR_LOG("open error");
    // 定位光标
    lseek(fd_src, offset, SEEK_SET);
    lseek(fd_dest, offset, SEEK_SET);
    // 拷贝
    char buff[10];
    int count = 0; // 已经读过的字节数
    int nbytes = 0;
    while(0 < (nbytes = read(fd_src, buff, sizeof(buff)))){
        count += nbytes;
        if(count >= cp_len){
            write(fd_dest, buff, cp_len-(count-nbytes));
            break;
        }
        write(fd_dest, buff, nbytes);
    }
    // 关闭文件
    close(fd_src);
    close(fd_dest);
}

int main(int argc, const char *argv[]){
    if(3 != argc){
        printf("Usage : %s src_file dest_file\n", argv[0]);
        return -1;
    }
    // 获取源文件大小 并 创建目标文件
    int length = get_srcfile_len_and_create_destfile(argv[1], argv[2]);
    pid_t pid = 0;
    if(-1 == (pid = fork())){
        ERR_LOG("fork error");
    }else if(0 < pid){// 父
        copy_file(argv[1], argv[2], 0, length/2);
    }else if(0 == pid){// 子
        copy_file(argv[1], argv[2], length/2, length-length/2);
    }
    return 0;
}